package cn.edu.imau.zy.auth.controller;

import cn.edu.imau.zy.auth.form.LoginForm;
import cn.edu.imau.zy.auth.service.AccessTokenService;
import cn.edu.imau.zy.auth.service.SysLoginService;
import cn.edu.imau.zy.captcha.model.common.ResponseModel;
import cn.edu.imau.zy.captcha.service.CaptchaService;
import cn.edu.imau.zy.common.core.domain.R;
import cn.edu.imau.zy.common.core.entity.system.SysUser;
import cn.edu.imau.zy.common.utils.StringUtils;
import cn.edu.imau.zy.system.weChat.WeChatApi;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@Slf4j
@Api("权限相关")
public class TokenController
{
    @Autowired
    private AccessTokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    @Lazy
    private CaptchaService captchaService;

    @Autowired
    private WeChatApi weChatApi;

    @PostMapping("login")
    public R login(@RequestBody LoginForm form)
    {
        // 用户登录
        SysUser user = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(user));
    }

    @ApiOperation(value = "appLogin", notes = "小程序帐号密码登录接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", required = true),
            @ApiImplicitParam(name = "password", value = "密码", required = true)})
    @PostMapping("appLogin")
    public R appLogin(@RequestBody LoginForm form)
    {
        System.out.println(form);
        System.out.println(form.getJscode() == null);
        // 用户登录
        SysUser user = null;
        try {
            user = sysLoginService.login(form.getUsername(), form.getPassword());
        } catch (Exception e) {
            return R.error("用户名/密码错误");
        }
        if (StringUtils.isNotEmpty(form.getJscode()) && StringUtils.isNotEmpty(user.getOpenId())) {
            JSONObject res = JSONObject.parseObject(weChatApi.jscode2session(form.getJscode()));
            if (res.get("openid") != null && !res.get("openid").toString().equals(user.getOpenId())) {
                return R.error("此帐号已绑定微信,请使用绑定微信登陆");
            }
        }
        // 获取登录token
        return R.ok(tokenService.createToken(user));
    }

    @ApiOperation(value = "wxLogin", notes = "微信号登陆接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "登陆码", required = true)})
    @PostMapping("wxLogin/{code}")
    public R wxLogin(@PathVariable("code") String code) {
        JSONObject res = JSONObject.parseObject(weChatApi.jscode2session(code));
        if (res.get("openid") != null) {
            SysUser userParams = new SysUser();
            userParams.setOpenId(res.get("openid").toString());
            // 用户登录
            SysUser user = sysLoginService.loginForWx(userParams);
            if (user != null) {
                return R.ok(tokenService.createToken(user)).put("openId", res.get("openid"));
            }
            // 获取登录token
        }
        // todo 下次更新可删除返回的openid
        return R.error("微信号未绑定，绑定后可快速登录哦~").put("openId", res.get("openid"));
    }

    @PostMapping("ssoLogin")
    public R ssoLogin(HttpServletRequest request)
    {
        String token = request.getHeader("token");
        SysUser user = tokenService.queryByToken(token);
        if(user == null){
            return R.error();
        }else {
            return R.ok(tokenService.updateToken(user,token));
        }
    }

    @PostMapping("login/slide")
    public R loginSilde(@RequestBody LoginForm form)
    {
        ResponseModel response = captchaService.verification(form.getVerify());
        if (response.isSuccess())
        {
            // 用户登录
            SysUser user = sysLoginService.login(form.getUsername(), form.getPassword());
            // 获取登录token
            return R.ok(tokenService.createToken(user));
        }
        return R.error().put("repCode", response.getRepCode());
    }

    @PostMapping("logout")
    public R logout(HttpServletRequest request)
    {
        String token = request.getHeader("token");
        SysUser user = tokenService.queryByToken(token);
        if (null != user)
        {
            sysLoginService.logout(user.getLoginName());
            tokenService.expireToken(Long.valueOf(user.getUserId()));
        }
        return R.ok();
    }
}
